package com.dagene.weixin.web;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dagene.weixin.JSONMessage;
import com.dagene.weixin.entity.Admin;
import com.dagene.weixin.service.AdminService;
import com.dagene.weixin.util.Constants;

@Controller
@RequestMapping(value = "/admin")
public class AdminController {
	@Autowired
	AdminService adminService;

	@RequestMapping(value = "/logon", method = RequestMethod.POST)
	@ResponseBody
	public JSONMessage logon(HttpServletRequest request,
			@RequestBody Admin admin) {
		JSONMessage message = new JSONMessage();
		try {
			Admin ad = adminService.getAdmin(admin.getUsername());
			if (ad == null || !ad.getPassword().equals(admin.getPassword())) {
				throw new Exception("账号或者密码错误!");
			} else {
				request.getSession().setAttribute("admin", admin.getUsername());
			}
		} catch (Exception e) {
			e.printStackTrace();
			message.setCode(Constants.ERROR_CODE);
			message.setMessage(e.getMessage());
		}
		return message;
	}

	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	@ResponseBody
	public JSONMessage logout(HttpServletRequest request) {
		JSONMessage message = new JSONMessage();
		try {
			request.getSession().removeAttribute("admin");
		} catch (Exception e) {
			e.printStackTrace();
			message.setCode(Constants.ERROR_CODE);
			message.setMessage(e.getMessage());
		}
		return message;
	}

	@RequestMapping(value = "/isLogin", method = RequestMethod.GET)
	@ResponseBody
	public JSONMessage isLogin(HttpServletRequest request) {
		JSONMessage message = new JSONMessage();
		try {
			if (request.getSession().getAttribute("admin") == null) {
				message.setCode(Constants.SESSION_TIMEOUT);
				// message.setData(Constants.weixinurl + "/admin/login.html");
			}
		} catch (Exception e) {
			e.printStackTrace();
			message.setCode(Constants.ERROR_CODE);
			message.setMessage(e.getMessage());
		}
		return message;
	}
}
